import java.util.HashMap;
import java.util.Map;

/**
 * @author LKQ
 * @date 2022/2/22 10:35
 * @description 桶排序
 */
public class FormalSolution2 {
    public static void main(String[] args) {
        FormalSolution2 fo = new FormalSolution2();
        int[] nums = {1,2,3,1};
        fo.containsNearbyAlmostDuplicate(nums, 3, 0);
    }
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        int n = nums.length;
        Map<Long, Long> map = new HashMap<Long, Long>();
        long w = (long) t + 1;
        for (int i = 0; i < n; i++) {
            long id = getID(nums[i], w);
            if (map.containsKey(id)) {
                return true;
            }
            if (map.containsKey(id - 1) && Math.abs(nums[i] - map.get(id - 1)) < w) {
                return true;
            }
            if (map.containsKey(id + 1) && Math.abs(nums[i] - map.get(id + 1)) < w) {
                return true;
            }
            map.put(id, (long) nums[i]);
            if (i >= k) {
                map.remove(getID(nums[i - k], w));
            }
        }
        return false;
    }
    public long getID(long x, long w) {
        // 桶排序，每个桶的范围 这里令 x = (t+1) * a + b; 使得 x 分布在编号a的桶
        if (x >= 0) {
            return x / w;
        }
        return (x + 1) / w - 1;
    }
}
